import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Table, 
  Input, 
  Button, 
  Space, 
  message,
  Modal,
  Form,
  TreeSelect,
  Tag
} from 'antd';
import { 
  SearchOutlined, 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined,
  EyeOutlined
} from '@ant-design/icons';
import { history, useModel } from '@umijs/max';
import { getCategories, deleteCategory, getCategoryTree } from '@/services/categoryApi';
import { CategoryItem } from '@/types/category';

const CategoryList: React.FC = () => {
  const [categories, setCategories] = useState<CategoryItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchForm] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [deleteCategoryId, setDeleteCategoryId] = useState<number | null>(null);
  const [treeData, setTreeData] = useState<any[]>([]);

  // 获取分类列表
  const fetchCategories = async (params = {}) => {
    setLoading(true);
    try {
      const { current = 1, pageSize = 10 } = pagination;
      const searchParams = {
        page: current,
        page_size: pageSize,
        ...params,
      };

      const res = await getCategories(searchParams);
      setCategories(res.data.results);
      setPagination({
        ...pagination,
        total: res.data.count,
      });
    } catch (error) {
      message.error('获取分类列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取分类树
  const fetchCategoryTree = async () => {
    try {
      const res = await getCategoryTree();
      setTreeData(res.data);
    } catch (error) {
      message.error('获取分类树失败');
    }
  };

  useEffect(() => {
    fetchCategories();
    fetchCategoryTree();
  }, [pagination.current, pagination.pageSize]);

  // 搜索
  const handleSearch = (values: any) => {
    fetchCategories(values);
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.resetFields();
    fetchCategories();
  };

  // 新增分类
  const handleAdd = () => {
    history.push('/categories/create');
  };

  // 编辑分类
  const handleEdit = (id: number) => {
    history.push(`/categories/edit/${id}`);
  };

  // 查看详情
  const handleView = (id: number) => {
    history.push(`/categories/detail/${id}`);
  };

  // 删除分类
  const handleDelete = (id: number) => {
    setDeleteCategoryId(id);
    setDeleteModalVisible(true);
  };

  // 确认删除
  const confirmDelete = async () => {
    if (deleteCategoryId === null) return;

    try {
      await deleteCategory(deleteCategoryId);
      message.success('删除成功');
      setDeleteModalVisible(false);
      fetchCategories();
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '分类名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: CategoryItem) => (
        <a onClick={() => handleView(record.id)}>{text}</a>
      ),
    },
    {
      title: '父级分类',
      dataIndex: 'parent',
      key: 'parent',
      render: (parent: any) => parent?.name || '-',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: CategoryItem) => (
        <Space>
          <Button 
            type="link" 
            icon={<EyeOutlined />} 
            onClick={() => handleView(record.id)}
          >
            查看
          </Button>
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => handleEdit(record.id)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            danger 
            icon={<DeleteOutlined />} 
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Form
            form={searchForm}
            layout="inline"
            onFinish={handleSearch}
          >
            <Form.Item name="name" label="分类名称">
              <Input placeholder="请输入分类名称" style={{ width: 200 }} />
            </Form.Item>
            <Form.Item name="parent" label="父级分类">
              <TreeSelect
                style={{ width: 200 }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeData={treeData}
                placeholder="请选择父级分类"
                treeDefaultExpandAll
                allowClear
              />
            </Form.Item>
            <Form.Item>
              <Space>
                <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
                  搜索
                </Button>
                <Button onClick={handleReset}>
                  重置
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </div>

        <div style={{ marginBottom: 16 }}>
          <Button 
            type="primary" 
            icon={<PlusOutlined />} 
            onClick={handleAdd}
          >
            添加分类
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={categories}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            onChange: (page, pageSize) => {
              setPagination({
                ...pagination,
                current: page,
                pageSize: pageSize,
              });
            },
          }}
        />
      </Card>

      {/* 删除确认模态框 */}
      <Modal
        title="确认删除"
        open={deleteModalVisible}
        onOk={confirmDelete}
        onCancel={() => setDeleteModalVisible(false)}
        okText="确认"
        cancelText="取消"
      >
        <p>确定要删除这个分类吗？此操作不可恢复。</p>
      </Modal>
    </div>
  );
};

export default CategoryList;